import React, { Component } from 'react';
import { View, Image, Text, FlatList, TouchableOpacity, ScrollView } from 'react-native';

import { storage, removeTokens, removeUserInfo } from '../utils/storage';

import request from '../utils/request'
var obj;

import navigationUtil from '../../src/utils/navigation'

import {HomeMessage} from './HomePages/HomeMessage'

//数据库
const Realm = require('realm');

let realm = new Realm({ schema: [HomeMessage]});

class Home extends Component {

   static navigationOptions =  {
    //stackNavigator的属性
    headerTitle: '消息',
    gestureResponseDistance: { horizontal: 300 },
    // headerBackTitle:'返回',     
    headerStyle: { backgroundColor: 'rgba(0,171,236,1)', height: 44 },//导航栏的样式
    headerTitleStyle: {//导航栏文字的样式
      color: 'white',
      //设置标题的大小
      fontSize: 20,
      //居中显示
      alignSelf: 'center',
    },
    headerRight:<TouchableOpacity  onPress={()=>obj.right()}> 
      <Image source={{uri:'扫一扫-发现'}} style={{marginRight:10,width:30,height:30}}></Image>
       </TouchableOpacity>,
    tabBarLabel: '消息',
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={require('../../images/ic_message.png')}
        style={[{ height: 24, width: 24 }, { tintColor: tintColor }]} />
    ),
  }

  right(){
    this.props.navigation.navigate('QRCodeScan', { title:'二维码' });
  }

  constructor(props) {
    super(props)

    this.state = {

      contentWait: '暂无消息',
      waitNum: 0,
      contentAlert: '暂无消息',
      alertNum: 0,
      contentWarm: '暂无消息',
      warmNum: 0,

    }
  }

  render() {
    obj = this;
    var dataSource = [
      { iconImg: '业务待办', name: '待办', content: this.state.contentWait, id: 0, num: this.state.waitNum },
      { iconImg: '审批结果', name: '提醒', content: this.state.contentAlert, id: 1, num: this.state.alertNum },
      { iconImg: '预警信息', name: '预警', content: this.state.contentWarm, id: 2, num: this.state.warmNum },
    ]

    return (

        <FlatList
          data={dataSource}
          keyExtractor={this._keyExtractor}
          renderItem={this._renderItem}
          ListHeaderComponent={this._listHeader}
        /> 

    );
  }

  itemClick = (rowData) => {

    this.props.navigation.navigate('MessageList', { rowData: rowData,title:' ' });

  }

  _renderItem(rowData) {


    return (<TouchableOpacity style={{
      padding: 15, flexDirection: 'row', alignItems: 'center',
      borderBottomColor: '#e8e8e8', borderBottomWidth: 0.5,backgroundColor:'white'
    }}
      onPress={() => obj.itemClick(rowData)}
    >

      <View style={{ marginRight: 20 }}>
        <Image source={{ uri: rowData.item.iconImg }} style={{ width: 40, height: 40 }}>
        </Image>
        {obj._numText(rowData)}
      </View>
      <View style={{ flex: 1, height: 40, justifyContent: 'space-between' }}>
        <Text style={{ fontSize: 18 }}>{rowData.item.name}</Text>
        <Text style={{ color: 'gray' }}>{rowData.item.content}</Text>
      </View>

    </TouchableOpacity>
    )
  }

  _numText = (rowData) => {
    if (rowData.item.num > 0) {
      return <Text style={{
        overflow: 'hidden', borderRadius: 13, lineHeight: 25,
        textAlign: 'center', backgroundColor: 'red', position: 'absolute',
        left: 25, top: -10, width: 25, height: 25,
        fontSize: rowData.item.num > 9 ? 9 : 15, color: 'white'
      }}>
        {rowData.item.num > 99 ? '99+' : rowData.item.num}
      </Text>
    }
    return null
  }



  _listHeader() {
    return (
      <View style={{ flexDirection: 'row', marginLeft: 10, marginTop: 3, marginRight: 10, borderRadius: 10, backgroundColor: '#e8e8e8', height: 44, alignItems: 'center' }}>
        <Image source={{ uri: '搜索bb' }}
          style={{ marginLeft: 10, width: 20, height: 20 }}
        />
        <Text style={{ marginLeft: 10 }}>搜索</Text>
      </View>
    )
  }
  _keyExtractor = (item, index) => {

    return (index + item.id)
  }

  componentDidMount() {

    storage.load({
      key: 'accessUserData'
    }).then(result => {

      request({
        method: 'POST',
        url: 'messages/queryWorkMessage',
        access_token: result.token,
      })
        .then((data) => {

          realm.write(() => {
            let HomeMessage = realm.objects('HomeMessage');
            // 删除
            realm.delete(HomeMessage);

            data.data.map(it => {
              realm.create('HomeMessage', {
                uuid: it.uuid,
                index: it.index,
                content: it.content,
                enContent: it.enContent,
                type: it.type,
                actionType: it.actionType,
                sendDate: it.sendDate,
                category: it.category,
                senderId: it.senderId,
                billFlag: it.billFlag
              })
            })
            let waitNum1 = HomeMessage.filtered('type == 0');
            let warmNum1 = HomeMessage.filtered('type == 2');
            let alertNum1 = HomeMessage.filtered('type == 1');

            var wait = '暂无消息';
            var alert = '暂无消息';
            var warm = '暂无消息';

            if (waitNum1.length > 0) {
              wait = waitNum1[0].content;
            }
            if (warmNum1.length > 0) {
              warm = warmNum1[0].content;
            }
            if (alertNum1.length > 0) {
              alert = alertNum1[0].content;
            }

            this.setState({
              waitNum: waitNum1.length,
              alertNum: alertNum1.length,
              warmNum: warmNum1.length,
              contentWait: wait,
              contentAlert: alert,
              contentWarm: warm,
            });
          })
        })
    })


  }

}

export function logOut() {

  removeTokens();
  removeUserInfo();
  navigationUtil.reset(obj.props.navigation, 'Login');
}

export default Home;




